import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/Home.vue'
import Notice from '@/notice.vue'
import Tree from '@/tree.vue'
import List from '@/routePage/list.vue'
import User from '@/routePage/user.vue'
import BreadCrumb from '@/routePage/BreadCrumb.vue'
import GlobalGuard from '@/routePage/GlobalGuard.vue'
import ExclusiveGuard from '@/routePage/exclusiveGuard.vue'
import ComponentGuard from '@/routePage/componentGuard.vue'

Vue.use(Router)

const router = new Router({
  // 模式：hash | history | abstract
  mode: 'history', 
  // 服务器地址，比如 http://localhost:8080/cart
  base: process.env.BASE_URL, 
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home,
      // 嵌套路由or路由传参
      children: [{
        path: "/list/:id",
        name: "List",
        component: List,
        props: true //路由参数以属性方式进行传递
      }]
    },
    {
      path: '/notice',
      name: 'Notice',
      component: Notice
    },
    {
      path: '/tree',
      name: 'Tree',
      component: Tree
    },
    {
      path: '/about',
      name: 'About',
      // 路由层级代码分割，生成分片(about.[hash].js)
      // 当路由访问时会懒加载
      component: () => import('@/routePage/about.vue')
    }, 
    {
      // 动态路由
      path: '/user/:id',
      name: 'User',
      component: User
    },
    {
      // 全局路由守卫
      path: '/globalGuard',
      name: 'GlobalGuard',
      component: GlobalGuard,
      // meta: {
      //   auth: true //需要验证
      // },
    },
    {
      // 路由独享守卫
      path: '/exclusiveGuard',
      name: 'ExclusiveGuard',
      component: ExclusiveGuard,
      beforeEnter(to, from, next) {
        if(!window.isLogin) { //未登录(路由内部知道自己需要验证)
          if(window.confirm("请登录-路由独享守卫")) {
            window.isLogin = true
            next() //登录成功，前往目标页面
          } else {
            next('/') //放弃登录，返回首页
          }
        } else { //已登录
          next()
        }
      },
    },
    {
      // 组件内路由守卫
      path: '/componentGuard',
      name: 'ComponentGuard',
      component: ComponentGuard,
      meta: {
        auth: true //需要验证
      },
    },
    {
      path: '/breadCrumb',
      name: 'BreadCrumb',
      component: BreadCrumb,
      children: [
        {
          path: '/about',
          name: 'About',
          component: () => import('@/routePage/about.vue')
        },
        {
          path: '/user/:id',
          name: 'User',
          component: User
        }
      ]
    }
  ]
})
// 全局路由守卫
// router.beforeEach((to,from,next)=>{
//   if(to.meta.auth && !window.isLogin) { //需要验证是否登录
//     if(window.confirm("请登录")) {
//       window.isLogin = true
//       next() //登录成功，前往目标页面
//     } else {
//       next('/') //放弃登录，返回首页
//     }
//   } else { //不需要验证或者已登录
//     next()
//   }
// })
export default router;